package com.zcx.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;


public class HttpUtil {
    public static String GET(String url, Map<String, String> params){
        try {
            url = url + "?";
            for(String key:params.keySet()){
                url += (key + "=" + params.get(key) + "&");
            }

            url = url.substring(0,url.length()-1);
            System.out.println("========"+url);
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len;
            while((len=is.read()) != -1){
                baos.write(len);
            }
            byte[] jsonBytes = baos.toByteArray();

            String message = new String(jsonBytes, "UTF-8");
            jsonBytes = null;
            is.close();
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static String sendFileReq(String url, MultipartEntityBuilder multipartEntityBuilder, String encoding) throws IOException {
        String body = "";

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost (url);

        //设置请求参数
        HttpEntity httpEntity = multipartEntityBuilder.build();

        httpPost.setEntity(httpEntity);

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }

    public static JSONObject POST(String url, Map<String, String> params){
        OutputStreamWriter out = null;
        try {
            URL urlPost = new URL(url);
            HttpURLConnection http = (HttpURLConnection)urlPost.openConnection();
            http.setRequestMethod("POST");
            // 发送POST请求必须设置为true
            http.setDoOutput(true);
            http.setDoInput(true);
            //设置连接超时时间和读取超时时间
            http.setConnectTimeout(30000);
            http.setReadTimeout(300000);
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            out = new OutputStreamWriter(http.getOutputStream());
            // POST的请求参数写在正文中
            for(String key:params.keySet()){
                out.write(key + "=" + params.get(key) + "&");
            }
            out.flush();
            out.close();

            // 取得输入流，并使用Reader读取
            InputStream is = http.getInputStream();
//            int size = is.available();
//            byte[] jsonBytes = new byte[size];
//            is.read(jsonBytes);



            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int next;
            while((next=is.read()) != -1){
                baos.write(next);
            }
            byte[] jsonBytes = baos.toByteArray();

            String message = new String(jsonBytes, "UTF-8");
            //System.out.println("return:"+message);

            JSONObject result = new JSONObject(message);
            is.close();
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally{//关闭输出流、输入流
            try{
                if(out!=null){
                    out.close();
                }
            } catch(IOException ex){
                ex.printStackTrace();
            }
        }
    }

}
